package com.dgl.sdk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Message;


public class FileCache {
	
	private static final String LOG_TAG = FileCache.class.getSimpleName();
	private static final int CACHE_SIZE = 1024*512;
	
	private File cacheDir;
	
	/**
     * 不用此方法了， 必须传缓存路径
	 * @param context
	 */
//	public FileCache(Context context) {
//
//		cacheDir = context.getCacheDir();
//		if(!cacheDir.exists()) {
//			mkDir(cacheDir);
//		}
//	}
	

	/**
	 * @param context cachePath
	 */
	public FileCache(Context context, String cachePath) {
		if((cachePath!=null)&&(cachePath!="")) {
			cacheDir = new File(cachePath);
		} else {
			cacheDir = context.getCacheDir();
		}
		if(!cacheDir.exists()) {
            boolean creatSuccess = mkDir(cacheDir);
            if(!creatSuccess){
                ToastShow.showToast(context, "存储卡没找到，可能导致软件未能正常使用！");
            }
		}
	}

    //递归创建文件夹
    private  boolean mkDir(File file) {
        if (file.getParentFile().exists()) {
            return file.mkdir();
        } else {
            mkDir(file.getParentFile());
            return file.mkdir();
        }
    }

	/**
	 * @param url
	 */
	public void addToFileCache(String url, InputStream inputStream) {
		OutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(getFromFileCache(url));
			copyStream(inputStream, outputStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if(outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void addToFileCache(String url, Bitmap bitmap) throws IOException {
		String fileName = urlToFileName(url);
		File file = new File(cacheDir, fileName);
	   
		FileOutputStream fOut = null;
	    try {
	            fOut = new FileOutputStream(file);
	    } catch (FileNotFoundException e) {
	            e.printStackTrace();
	    }
	    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
	    try {
	            fOut.flush();
	    } catch (IOException e) {
	            e.printStackTrace();
	    }
	    try {
	            fOut.close();
	    } catch (IOException e) {
	            e.printStackTrace();
	    }
	}
	
	//加密保存
//	public void addToEncryptFileCache(final String url, final Bitmap bitmap) {
//
//		
//        new Thread(){
//
//			@Override
//			public void run() {
//				
//				File tempFile = new File(cacheDir, "tmp");
//				
//				FileOutputStream fOut = null;
//			    try {
//			            fOut = new FileOutputStream(tempFile);
//			    } catch (FileNotFoundException e) {
//			            e.printStackTrace();
//			    }
//			    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
//			    try {
//			            fOut.flush();
//			    } catch (IOException e) {
//			            e.printStackTrace();
//			    }
//			    try {
//			            fOut.close();
//			    } catch (IOException e) {
//			            e.printStackTrace();
//			    }
//				
//			    String fileName = urlToFileName(url);
//				File encryptFile = new File(cacheDir, fileName);
//				
//				try {
//					InputStream in = new FileInputStream(tempFile);
//					OutputStream out = new FileOutputStream(encryptFile);
//
//					String key = DESUtils.getSecretKey(ConstValue.DES_KEY);
//					Key k = toKey(Base64Utils.decode(key));
//					Cipher cipher = Cipher.getInstance(DESUtils.ALGORITHM);
//					cipher.init(Cipher.DECRYPT_MODE, k);
//					CipherOutputStream cout = new CipherOutputStream(out,
//							cipher);
//					byte[] cache = new byte[CACHE_SIZE];
//					int nRead = 0;
//
//					while ((nRead = in.read(cache)) != -1) {
//						cout.write(cache, 0, nRead);
//						cout.flush();
//
//					}
//					cout.close();
//					in.close();
//				} catch (Exception e) {
//				}
//
//			}
//
//		}.start();
//		
//	}
//	
//    private static Key toKey(byte[] key) throws Exception {
//        DESKeySpec dks = new DESKeySpec(key);
//        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DESUtils.ALGORITHM);
//        SecretKey secretKey = keyFactory.generateSecret(dks);
//        return secretKey;
//    }
    
	public File getFromFileCache(String url) {
		String fileName = urlToFileName(url);
		File file = new File(cacheDir, fileName);
		return file;
	}
	
	public String GetImageFilePath(String url){
		return cacheDir.getAbsolutePath()  + urlToFileName(url);
	}
	
	public String GetImageFileDir(){
		return getFileCacheDir();
	}

    /**
     * 获取catch路径
     * @return
     */
    public String getFileCacheDir(){
        return cacheDir.getAbsolutePath()+ "/" ;
    }

    /**
     * 根据url 返回存储的绝对路径 全路径
     * @param url
     * @return
     */
    public String getAbsolutePathByUrl(String url){
        return cacheDir.getAbsolutePath() + "/" + urlToFileName(url);
    }


	public void DeleteTempFile(){
		File file = new File(GetImageFileDir()+"temp");
		file.delete();
	}
	
	/**
	 * 濞�拷��拷锟芥�缂�拷锟�	 */
	public void clearCache() {
		File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
	}
	
	
	/**
	 * 
	 * @param url
	 * @return
	 */
	public static String urlToFileName(String url) {
		return String.valueOf(url.hashCode());
	}
	
	private void copyStream(InputStream is, OutputStream os){
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }



}
